<template>
  <a-layout>
    <a-layout-header>
      <a-select :defaultValue="keywords" mode="multiple" style="width: 100%" @change="handleChange">
        <template v-for="tag in tags">
          <a-select-option :key="tag">{{tag}}</a-select-option>
        </template>
      </a-select>
    </a-layout-header>
    <a-layout-content style="padding: 15px 30px; box-sizing: border-box;">
      <a-row type="flex" :gutter="[16, 16]">
        <template v-for="route in routes">
          <a-col :key="route.name">
            <a-card  hoverable style="width: 300px" @click="(e) => handleClick(route, e)">
              <img :src="route.image" :alt="route.title" width="300px" height="180px" slot="cover"/>
              <a-card-meta :title="route.title" :description="route.description" />
            </a-card>
          </a-col>
        </template>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>

<script>
  import {intersection, debounce} from 'lodash';
  import {createNamespacedHelpers} from 'vuex';

  const {mapState} = createNamespacedHelpers('pages');

  export default {
    name: 'home',

    data () {
      return {
        keywords: [],
        routes: []
      }
    },

    computed: {
      ...mapState({
        pages: state => state['pages'] || [],
        tags: state => state['tags'] || []
      }),
    },

    methods: {
      handleChange: debounce(function (keywords = []) {
        const routes = this.pages.filter(({tags}) => {
          const array = intersection(tags, keywords);
          return array.length === keywords.length;
        });
        this.$set(this.$data, 'keywords', keywords);
        this.$set(this.$data, 'routes', routes);
      }, 600),
      handleClick (route) {
        const location = this.$router.resolve({name: route.name});
        window.open(location.href, '_blank');
      },
    },

    mounted() {
      this.handleChange([], []);
    }
  }
</script>
